<template>
  <div class="w-full h-full min-h-screen box-border relative">  
    <van-nav-bar 
      left-arrow 
      :title="$t('pageTitle.withdraw')" 
      @click-left="router.back()" 
      safe-area-inset-top 
    />
    <van-config-provider :theme-vars="themeVars">
      <van-form @submit="submit" class="!mx-4 !mt-4">
        <div class="!text-[14px]">
          <span class="mr-1">
            {{ $t('currentAccountBalance') }}:
          </span>
          <span class="!text-red-600">{{ balance }}</span>
        </div>
        <van-field 
          label=" "
          v-model="params.money"  
          name="money" 
          type="digit"
          clearable
          class="!mt-4 border-solid border-[1px] rounded"
          label-width="0rem"
          :placeholder="$t('placeholder.enterWithdrawalPrice')" 
          :rules="rules.moneyRules" 
        />
        <div class="!text-[14px] mt-4">
          {{ $t('placeholder.bindWithdrawalCard') }}: 
        </div>
        <div class="border-solid border-[1px] box-border p-3 rounded mt-4 text-[14px] cursor-pointer">
          <template v-if="showBank">
              <div 
                class="w-full pl-2 box-border py-4 text-[#8f8f94]" 
                @click="router.push('/bank')"
                >
                {{ $t('toBindBank') }}
              </div>
          </template>
          <template v-else>
            <div>
              <span class="mr-1">{{ $t('label.payAccount') }}:</span>
              <span>{{ bankNoFormat(user.defaultBank.accountNo ) }}</span>
            </div>
            <div class="!mt-1">
              <span class="mr-1">{{ $t('label.payBank') }}:</span>
              <span>{{ user.defaultBank.bankName }}</span>
            </div>
          </template>
        </div>
        <div class="!text-[14px] mt-4">
          {{ $t('withdrawalPassword') }}: 
        </div>
        <van-field 
          label=" "
          v-model="params.password"  
          name="password" 
          type="digit"
          clearable
          class="!mt-4 border-solid border-[1px] rounded"
          label-width="0rem"
          :placeholder="$t('placeholder.enterWithdrawalPassWord')" 
          :rules="rules.passwordRules" 
        />
        <div class="mt-14 mx-4">
          <van-button 
            round 
            block 
            type="primary" 
            native-type="submit" 
            color="#000"
            :loading="loading"
          >
            <span class="text-white text-[16px]">
              {{ $t('btnText.submitApplication') }}
            </span>
          </van-button>
        </div>
      </van-form>
    </van-config-provider>
    <RechargeFooter />
    <van-number-keyboard safe-area-inset-bottom />
  </div>
</template>
<script setup lang="ts">
import RechargeFooter from "@/components/RechargeFooter/index.vue"

import { showDialog, showFailToast, showToast } from "vant"

import { useRouter } from "vue-router"

import { useI18n } from 'vue-i18n'

import { useUserStore } from "@/store/user"

import { Decimal } from "decimal.js"

import { bankNoFormat } from "@/utils/format"

import { createWithdraw } from "@/service/login"

const router = useRouter()

const user = useUserStore()

onBeforeMount(() => {
  user.loadDefaultBank()
  user.loadWallet()
})

const { t } =  useI18n({ useScope: 'global' })

const showBank = computed(() => !!!user.defaultBank)

const balance = computed(() => new Decimal((user?.wallet?.balance || 0)).toFixed(2))

const themeVars = {
  cellVerticalPadding: "8px",
  fieldLabelMarginRight: 0
}

const loading = ref<boolean>(false)

const params = ref({
  money: "",
  password: ""
})

const rules: any = {
  moneyRules: [{ 
    required: true, message: t('placeholder.enterWithdrawalPrice'), trigger: 'onBlur'
  }],
  passwordRules: [{ 
    required: true, message: t('rule.withdrawalPassWordNotEmpty'), trigger: 'onBlur' 
  }],
}

const submit = async () => {
  try {
    if(showBank.value) return showFailToast(t('placeBindBank'))

    if(!user.wallet.hasPassword) {
      return showDialog({
        title:  t('logoutTipsTitle'),
        message: t('nonePassWord')
      }).then(() => router.push('/withdrawPass'))
      .catch(() => {})
    }

    loading.value = true

    const res = await createWithdraw({
      payPassword: params.value.password,
      bankName: user.defaultBank.bankName,
      accountNo: user.defaultBank.accountNo,
      realname: user.defaultBank.realname,
      money: params.value.money,
      currency: user.wallet.currency
    })

    loading.value = false

    if(!res.success) return

    showToast(res.message)

  } catch(err){
    loading.value = false
    throw err
  }
}
</script>

<style lang="less" scoped>
:deep(.van-field__error-message) {
  position: absolute;
  top: 0;
  left: 50%;
}
</style>
